package com.demo.dao;

import com.demo.dao.mapper.RegisterMapper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class RegisterDao extends BaseDao {
    private static final String ENVIRONMENT_HOMER = "HOMER";
    private static final String ENVIRONMENT_CU = "CU";
    private static final String ENVIRONMENT_HP = "HP";

    public Login selectLoginElement(String personId, String phoneNumber) {
        Login login = new Login();
        try (SqlSession session = openSession(ENVIRONMENT_CU)) {
            int count = 1;

            do {
                RegisterMapper mapper = session.getMapper(RegisterMapper.class);
                login = mapper.selectLoginElement(personId, phoneNumber);

                if (count == 10) {
                    break;
                }
                count++;
            } while (login == null);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return login;
    }

    public Login selectLoginElementByPersonId(String personId){
        Login login = new Login();

        try (SqlSession session = openSession(ENVIRONMENT_CU)){
            RegisterMapper mapper = session.getMapper(RegisterMapper.class);
            login = mapper.selectLoginElementByPersonId(personId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return login;
    }

    public Register checkRegister(String personId) {
        Register register = null;
        List<Register> registerList = null;

        try (SqlSession session = openSession(ENVIRONMENT_CU)){
            RegisterMapper mapper = session.getMapper(RegisterMapper.class);
            registerList = mapper.checkRegister(personId);
            //如果有多条状态为a的数据，取第一条，环境异常时会存在这种情况
            if (registerList.size() != 0) {
                register = registerList.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return register;
    }
}
